package com.example.es.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;

@Configuration
public class ElasticsearchConfig {

    /**
     * elk集群地址
     */
    @Value("${elasticsearch.ip}")
    private String hostName;

    /**
     * 端口
     */
    @Value("${elasticsearch.port}")
    private Integer port;

    /**
     * scheme
     */
    @Value("${elasticsearch.scheme}")
    private String scheme;

    /**
     * socket 超时
     */
    @Value("${elasticsearch.socketTimeOut}")
    private Integer socketTimeOut;

    /**
     * 连接超时
     */
    @Value("${elasticsearch.connectTimeOut}")
    private Integer connectTimeOut;

    /**
     * 请求超时
     */
    @Value("${elasticsearch.connectionRequestTimeOut}")
    private Integer connectionRequestTimeOut;

    @Bean(destroyMethod = "close")
    public RestHighLevelClient restHighLevelClient() {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                //es账号密码
                new UsernamePasswordCredentials("elastic", "liufeng"));
        return new RestHighLevelClient(
                RestClient.builder(new HttpHost(hostName, port, scheme))
                        .setRequestConfigCallback(
                                requestConfigBuilder -> {
                                    // 设置相关连接配置
                                    requestConfigBuilder.setConnectTimeout(connectTimeOut * 1000);
                                    requestConfigBuilder.setSocketTimeout(socketTimeOut * 1000);
                                    requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeOut * 1000);
                                    return requestConfigBuilder;
                                }
                        ).setHttpClientConfigCallback(httpClientBuilder -> {
                    //这里可以设置一些参数，比如cookie存储、代理等等
                    httpClientBuilder.disableAuthCaching();
                    return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                }));
    }
}